import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import Layout from '../layouts/Layout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login/index.vue'),
      meta: { requiresAuth: false, title: '登录' }
    },
    {
      path: '/',
      name: 'layout',
      component: Layout,
      redirect: '/activities',
      children: [
        {
          path: 'activities',
          name: 'activities',
          component: () => import('../views/activities/Index.vue'),
          meta: { title: '活动管理' }
        },
        {
          path: 'articles',
          name: 'articles',
          component: () => import('../views/articles/Index.vue'),
          meta: { title: '文章管理' }
        },
        {
          path: 'gifts',
          name: 'gifts',
          component: () => import('../views/gifts/Index.vue'),
          meta: { title: '礼品管理' }
        },
        {
          path: 'activity-types',
          name: 'activity-types',
          component: () => import('../views/activity-types/Index.vue'),
          meta: { title: '活动类型管理' }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  document.title = `${to.meta.title} - 校园活动管理系统`
  
  if (to.path === '/login') {
    if (authStore.token) {
      next('/activities')
    } else {
      next()
    }
  } else {
    if (authStore.checkAuth()) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router 